package com.wlxk.crawler.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wlxk.crawler.core.dao.ChapterDAO;
import com.wlxk.crawler.core.entity.ChapterDO;
import com.wlxk.crawler.core.enums.SourceEnum;
import com.wlxk.crawler.core.exception.WlxkException;
import com.wlxk.crawler.core.service.IGrabService;
import com.wlxk.crawler.core.service.ISyncService;
import com.wlxk.crawler.core.util.HttpClientDownloader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import us.codecraft.webmagic.Spider;

import java.util.List;

/**
 * @description:
 * @author: 21054523
 * @time: 2023/10/25 14:32
 */
@Service
public class GrabServiceImpl implements IGrabService {

    @Autowired
    private ChapterDAO chapterDAO;

    @Autowired
    private ISyncService syncService;

    @Override
    public void grabArticleInfo(String url) {
        SourceEnum sourceEnum = SourceEnum.getByUrl(url);
        if (null == sourceEnum) {
            throw new WlxkException("地址不支持抓取");
        }
        Spider.create(sourceEnum.getPageProcessor()).addPipeline(sourceEnum.getPipelineBean())
                .setDownloader(new HttpClientDownloader()).addUrl(url).thread(1).run();
    }

    @Override
    public void grabUnSyncChapterInfo() {
        List<ChapterDO> chapterDOS = chapterDAO.selectList(
                new LambdaQueryWrapper<ChapterDO>().eq(ChapterDO::getStatus, 0));
        if (!CollectionUtils.isEmpty(chapterDOS)) {
            chapterDOS.forEach(syncService::syncChapter);
        }
    }

}
